package com.yu.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yu.crm.domain.pojo.AttendanceInfo;
import com.yu.crm.domain.pojo.AttendanceRecord;
import com.yu.crm.domain.pojo.AttendanceSet;
import com.yu.crm.mapper.AttendanceRecordMapper;
import com.yu.crm.utils.HolidayUtil;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.DateHelpers;
import com.yxzz.common.helper.ResourceConfigHelpers;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 考勤记录表 服务实现类
 * </p>
 *
 * @author ct
 * @since 2019-12-31
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class AttendanceRecordService extends ServiceImpl<AttendanceRecordMapper, AttendanceRecord>{
    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    private static DateFormat df1 = new SimpleDateFormat("HH:mm");
    private static DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    AttendanceInfoService attendanceInfoService;
    @Autowired
    AttendanceSetService attendanceSetService;
    @Autowired
    ObjectMapper objectMapper;

    /**
     * 新增考勤记录
     * @param userIds
     * @return
     */
    public Long add(String userIds) {
        try {
            if(DataHelpers.isEmpty(userIds)){
                throw new GeneralException("未传用户id");
            }
            List<String> list=objectMapper.readValue(userIds, new TypeReference<List<String>>() {});
            if(DataHelpers.isNotEmpty(list)){
                for(String userId:list){
                    AttendanceSet attendanceSet = attendanceSetService.infoByUserId(userId);
                    if(DataHelpers.isNotEmpty(attendanceSet)){
                        //DateTimeFormatter df3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        //LocalDateTime attendanceTime = LocalDateTime.parse(csTime,df3);
                        LocalDateTime attendanceTime = LocalDateTime.now();
                        AttendanceRecord attendanceRecord=new AttendanceRecord();
                        attendanceRecord.setUserId(userId);
                        attendanceRecord.setAttendanceTime(attendanceTime);
                        attendanceRecord.setGmtCreate(LocalDateTime.now());
                        attendanceRecord.setGmtModified(LocalDateTime.now());
                        if(save(attendanceRecord)) {
                            //开始日期
                            Integer startDate = Integer.parseInt(attendanceSet.getAttendanceStartDate().replace("-", ""));
                            Integer endDate = Integer.parseInt(attendanceSet.getAttendanceEndDate().replace("-", ""));
                            //开始时间
                            Integer amStartTime = Integer.parseInt(attendanceSet.getAttendanceAmStartTime().replace(":", ""));

                            //结束时间
                            Integer pmEndTime = Integer.parseInt(attendanceSet.getAttendancePmEndTime().replace(":", ""));
                            //当前时间
                            String formatYmd = df.format(DateHelpers.localDateTimeToLong(attendanceTime));
                            String formatHmString = df1.format(DateHelpers.localDateTimeToLong(attendanceTime));
                            Integer formatYmdInteger = Integer.parseInt(formatYmd.replace("-", ""));
                            //当前时间
                            Integer formatHm = Integer.parseInt(df1.format(DateHelpers.localDateTimeToLong(attendanceTime)).replace(":", ""));
                            // 1 正常 2 加班 3 迟到 4 早退 5 缺勤
                            Integer amStatus = 1;
                            String amTime = "";
                            // 1 正常 2 加班 3 迟到 4 早退 5 缺勤
                            Integer pmStatus = 1;
                            String pmTime = "";
                            Boolean flag = false;
                            if (startDate <= formatYmdInteger && formatYmdInteger <= endDate) {
                                AttendanceInfo attendanceInfo = attendanceInfoService.infoByUserId(userId, formatYmd);
                                if (DataHelpers.isNotEmpty(attendanceInfo)) {
                                    //最后一次打卡
                                    if (DataHelpers.isNotInteger(attendanceInfo.getPmStatus())) {
                                        pmStatus = attendanceInfo.getPmStatus();
                                        pmTime = attendanceInfo.getPmTime();
                                    }
                                    if (DataHelpers.isNotInteger(attendanceInfo.getAmStatus())) {
                                        amStatus = attendanceInfo.getAmStatus();
                                        amTime = attendanceInfo.getAmTime();
                                    }

                                    if (formatHm < pmEndTime) {
                                        pmTime = formatHmString;
                                        pmStatus = 4;
                                    } else if (formatHm >= pmEndTime) {
                                        pmTime = formatHmString;
                                        pmStatus = 1;
                                        flag = true;
                                    }
                                } else {
                                    attendanceInfo = new AttendanceInfo();
                                    attendanceInfo.setStatus(1);
                                    amTime = formatHmString;
                                    //第一次打卡
                                    attendanceInfo.setGmtCreate(LocalDateTime.now());
                                    if (formatHm > amStartTime) {
                                        amStatus = 3;
                                    }
                                }
                                Integer time = (formatHm - pmEndTime) / 100;
                                Integer property = Integer.parseInt(ResourceConfigHelpers.getProperty("attendance.overtime"));
                                System.out.println("加班时长------------"+time);
                                if (time>=property) {
                                    //说明加班了
                                    Integer request = HolidayUtil.request(formatYmd);
                                    if (request != null && request == 0) {
                                        if (flag) {
                                            //设置加班时长
                                            if (property <= time) {
                                                pmTime = formatHmString;
                                                //工作日加班
                                                pmStatus = 2;
                                                attendanceInfo.setStatus(2);
                                            }
                                        }
                                    } else {
                                        //节假日加班
                                        amStatus = 2;
                                        if (DataHelpers.isEmpty(attendanceInfo.getAmTime())) {
                                            amTime = formatHmString;
                                        }
                                        pmStatus = 2;
                                        pmTime = formatHmString;
                                        attendanceInfo.setStatus(2);
                                    }
                                }

                                /*Integer request = HolidayUtil.request(formatYmd);
                                System.out.println("request------------"+request);
                                if (request != null && request == 0) {
                                    if (flag) {
                                        //设置加班时长
                                        Integer property = Integer.parseInt(ResourceConfigHelpers.getProperty("attendance.overtime"));
                                        //加班时长
                                        Integer time = (formatHm - pmEndTime) / 100;
                                        System.out.println("time------------"+time);
                                        if (property <= time) {
                                            pmTime = formatHmString;
                                            //工作日加班
                                            pmStatus = 2;
                                            attendanceInfo.setStatus(2);
                                        }
                                    }
                                } else {
                                    //节假日加班
                                    amStatus = 2;
                                    if (DataHelpers.isEmpty(attendanceInfo.getAmTime())) {
                                        amTime = formatHmString;
                                    }
                                    pmStatus = 2;
                                    pmTime = formatHmString;
                                    attendanceInfo.setStatus(2);
                                }*/

                                if (amStatus > 2 || pmStatus > 2) {
                                    attendanceInfo.setStatus(3);
                                } else {
                                    if (attendanceInfo.getStatus() != 2) {
                                        attendanceInfo.setStatus(1);
                                    }
                                }

                                attendanceInfo.setAmTime(amTime);
                                attendanceInfo.setPmTime(pmTime);
                                attendanceInfo.setAmStatus(amStatus);
                                attendanceInfo.setPmStatus(pmStatus);
                                attendanceInfo.setUserId(userId);
                                attendanceInfo.setGmtModified(LocalDateTime.now());
                                attendanceInfo.setRecordTime(formatYmd);
                                //添加当天考勤记录
                                attendanceInfoService.saveOrUpdate(attendanceInfo);
                            }
                            return attendanceRecord.getId();
                        }
                    }else{
                        //throw new GeneralException("未设置考勤,无法统计考勤");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("新增考勤记录失败");
            throw new GeneralException("新增考勤记录失败");
        }
        return null;
    }
}
